package bc.swim2.ejb.session;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import bc.swim2.ejb.entity.Admin;
import bc.swim2.ejb.entity.RegisteredUser;

/**
 * Session Bean implementation class RegistrationManager
 */
@Stateless
public class RegistrationBean implements RegistrationBeanRemote {

	/**
	 * Default constructor.
	 */
	public RegistrationBean() {
	}

	@PersistenceContext(unitName = "swimv2")
	private EntityManager em;

	@SuppressWarnings("unchecked")
	@Override
	public boolean isAlreadyRegistered(RegisteredUser reguser) {

		boolean isAlreadyRegistered = false;
		
		List<RegisteredUser> users = null;

		try {
			Query q = em.createNamedQuery("RegisteredUser.getRegisteredUserByUsername");
			q.setParameter("username", reguser.getUsername());

			users = (List<RegisteredUser>) q.getResultList();

		} catch (Exception e) {
			e.printStackTrace();
		}

		if (!(users.isEmpty())) {
			isAlreadyRegistered = true;
		} else {
			
			List<Admin> admins = null;
			try {
				Query q = em.createNamedQuery("Admin.getAdminByUsername");
				q.setParameter("username", reguser.getUsername());

				admins = (List<Admin>) q.getResultList();
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			if (!(admins.isEmpty())) {
				isAlreadyRegistered = true;
			}
			
			List<RegisteredUser> registeredUsers = null;
			try {
				Query p = em
						.createNamedQuery("RegisteredUser.getRegisteredUserByEmail");
				p.setParameter("email", reguser.getEmail());

				registeredUsers = (List<RegisteredUser>) p.getResultList();

			} catch (Exception e) {
				e.printStackTrace();
			}

			if (!(registeredUsers.isEmpty())) {
				isAlreadyRegistered = true;
			}
			
		}

		return isAlreadyRegistered;
	}

	@Override
	public void register(RegisteredUser reguser) {
		try {
			em.persist(reguser);
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
	}
}
